import showMsg from '../utils/errmsg'
import Cookies from 'js-cookie'
import { httpHeader } from './../utils/http'
function getCookie(key,cookies){
    var arr1=cookies.split("; ");
    for(var i=0;i<arr1.length;i++){
        var arr2=arr1[i].split("=");
        if(arr2[0]==key){
            return decodeURI(arr2[1]);
        }
    }
}
const inBrowser = typeof window !== 'undefined'
export const state = () => {
    return {
        token: '',
        userInfo: null,
        userType: null,
        selectedTab: '',
        userMenuTagName: '',
        loginDialogVisible: false,
        messageStats: {
            notice: 0
        }
    }
}

export const mutations = {
    HANDLE_LOGIN (state, visible) {
        state.loginDialogVisible = visible
    },

    // 存用户
    SET_USER(state, { user, expires }) {
        // state.userInfo = user || null
        // if (inBrowser) {
        //     if (user) {
        //         Cookies.set('userInfo', user)
        //     } else {
        //         Cookies.remove('userInfo')
        //     }
        // }
        state.userInfo = user
        if (inBrowser) {
            if (!user) {
                return Cookies.remove('userInfo')
            } else {
                // console.log('setToken')
                Cookies.set('userInfo', user, { expires })
            }
        }

    },
    // 存个人或企业
    SET_TYPE(state, type) {
        state.userType = type || null
        if (inBrowser) {
            Cookies.set('type', type)
        }
    },
    // 设置token
    SET_TOKEN(state, { token, expires }) {
        state.token = token
        if (inBrowser) {
            if (!token) {
                // console.log('removeToken')
                return Cookies.remove('token')
            } else {
                // console.log('setToken')
                Cookies.set('token', token, { expires })
            }
        }
    },

    SET_SELECTED_TAB (state, name) {
        state.selectedTab = name
    },

    setUserMenuTagName(state, payload) {
        state.userMenuTagName = payload
    },

    SET_MESSAGE_STATS (state, count) {
        state.messageStats.notice = count
    }
}
export const actions = {
    // 登录
    async login({commit, dispatch, redirect }, payload) {
        try {
            const response = await this.$axios.$post('/api/login', payload, httpHeader)
            const tokenPart = response.data
            // 有效期 1 天
            const expires = this.$moment().add(1, 'days').toDate()
            console.log('response::',response.message,response,tokenPart)
            if (response.message === '认证成功') {
                commit('SET_TOKEN', { token: tokenPart.token, expires })


                // 控制台需要相关信息
                localStorage.setItem('EXPIRE_TIME', JSON.stringify(tokenPart.exipreTime))
                localStorage.setItem('PERMISSIONS', JSON.stringify(tokenPart.permissions))
                // const user = {...tokenPart}
                // delete user.token
                // commit('SET_USER', user.user)
                commit('SET_USER', { user: tokenPart.user, expires })
            } else {
                throw response
            }
        } catch (err) {
            throw err
        }
        // await dispatch('fetchLoggedUser')

        // if (inBrowser && 'localStorage' in window) {
        //     window.localStorage.clear()
        // }
    },
    // 手机号登录
    async loginMobile({commit, dispatch, redirect }, payload) {
        try {
            const response = await this.$axios.$post('/api/login/mobile', payload, httpHeader)
            const tokenPart = response.data
            // 有效期 10 天
            const expires = this.$moment().add(1, 'days').toDate()
            if (response.message === '认证成功') {
                commit('SET_TOKEN', { token: tokenPart.token, expires })
                // 控制台需要相关信息
                localStorage.setItem('EXPIRE_TIME', JSON.stringify(tokenPart.exipreTime))
                localStorage.setItem('PERMISSIONS', JSON.stringify(tokenPart.permissions))
                // const user = {...tokenPart}
                // delete user.token
                // commit('SET_USER', user.user)
                commit('SET_USER', { user: tokenPart.user, expires })
            } else {
                throw response
            }
        } catch (err) {
            throw err
        }
        // await dispatch('fetchLoggedUser')

        // if (inBrowser && 'localStorage' in window) {
        //     window.localStorage.clear()
        // }
    },

    // 用户登录退出
    async logout ({ commit, dispatch }, payload) {
        // console.log('logout commit:',commit,dispatch,payload)
        try {
            // const response = await this.$axios.$post('/api/loginOut')
            commit('SET_TOKEN', { token: null })
            commit('SET_USER', { user: null })
            if (inBrowser) {
                window.localStorage.clear()
            }
        } catch (err) {
            if (inBrowser) {
                throw err
            }
        }
    },
    /*  
        字典表
        车辆类型 5
        车皮类型 10
        公路运输类型 11
        铁路运输类型 12
        海路运输类型 13
        航空公司列表 14
    */
    async infoCommonDict({ commit, dispatch }, payload) {        
        try {
            const response = await this.$axios.$get('/api/info/commonDict', { params: payload }, httpHeader)
            response.status = response.code === '0000'
            if (!response.status) showMsg(response.message, response.code, dispatch)
            return response
        } catch (err) {
            err.status = false
            return err
        }
    },
    /*
     验证码
     type: login(登录)、regist(注册)、reset(重置密码)、other(其他)
     mobile: mobile
     imgCode: 注册时必填
    */
    async SmsMsgSend({ commit, dispatch }, payload) {        
        try {
            const response = await this.$axios.$post('/api/info/smsMsg/open/send', payload, httpHeader)
            response.status = response.code === '0000'
            if (!response.status) showMsg(response.message, response.code, dispatch)
            return response
        } catch (err) {
            err.status = false
            return err
        }
    },
    /*
     验证验证码
     mobile: mobile
     smsMsgCode: 短信验证码
    */
    async SmsMsgVerify({ commit, dispatch }, payload) {        
        try {
            const response = await this.$axios.$post('/api/info/smsMsg/open/verify', payload, httpHeader)
            response.status = response.code === '0000'
            if (!response.status) showMsg(response.message, response.code, dispatch)
            return response
        } catch (err) {
            err.status = false
            return err
        }
    },
    // 根据手机号码重置密码
    async passwordResetMobile({ commit, dispatch }, payload) {        
        try {
            const response = await this.$axios.$put('/api/user/open/password/reset/mobile', payload, httpHeader)
            response.status = response.code === '0000'
            if (!response.status) showMsg(response.message, response.code, dispatch)
            return response
        } catch (err) {
            err.status = false
            return err
        }
    },
    // 查询当前用户未读消息
    async getUserinfoCountList({ commit, dispatch }, payload) {        
        try {
            const response = await this.$axios.$get('/api/userinfo/getUserinfoCountList', payload, httpHeader)
            response.status = response.message === '查询成功'
            if (!response.status) showMsg(response.message, response.code, dispatch)
            return response
        } catch (err) {
            err.status = false
            return err
        }
    },


    // async fetchLoggedUser({ commit, state }) {
    //     try {
    //         const response = await this.$axios.$get('/api/users/me')
    //         if (response.code === 200) {
    //             commit('SET_USER', response.data || {})
    //         } else {
    //             throw { code: response.cdoe }
    //         }
    //     } catch (err) {
    //         if (err.code === 415 || err.code === 413) {
    //             commit('SET_TOKEN', { token: null })
    //         } else {
    //             throw err
    //         }
    //     }
    // },

    // async fetchMessageStats ({ commit }) {
    //     try {
    //         const { code, data } = await this.$axios.$post('/api/userServe/getUMessage')
    //         if (code === 200) {
    //             commit('SET_MESSAGE_STATS', data)
    //         }
    //     } catch (err) {
    //     }
    // },

    async nuxtServerInit({ commit, dispatch, state }, { app, req }) {
        // console.log('nuxtServerInit req ---:',req)
        // console.log('nuxtServerInit app ---:',app)
        if (process.client) {
            window.history.replaceState = window.history.replaceState || function () {}
        }

        const token = req.headers.cookie && getCookie('token',req.headers.cookie)
        const userInfo = req.headers.cookie && decodeURIComponent(getCookie('userInfo',req.headers.cookie))
        console.log('userInfo:::',token,userInfo)
        // console.log('token userInfo:',token,userInfo)
        if (token) {
            commit('SET_TOKEN', { token })
            // await dispatch('fetchMessageStats')
            
            if (userInfo&&userInfo!='undefined') {
                commit('SET_USER', { user: JSON.parse(userInfo) })
            } else {
                // await dispatch('fetchLoggedUser')
            }
        } else {
            // dispatch('logout')
        }
        
        // commit('SET_TYPE', req.cookies&&req.cookies.type || null)
    }
}
